import { service } from "@/utils/RobApi"

// 文件对象接口
interface FileObject {
    type: 'image' | 'audio' | 'video' | 'document' | 'custom'
    transfer_method: 'remote_url' | 'local_file'
    url?: string
    upload_file_id?: string
}

// 发送消息请求接口
interface SendMessageRequest {
    inputs: Record<string, any>
    query: string
    response_mode: 'streaming' | 'blocking'
    conversation_id?: string
    user: string
    files?: FileObject[]
    auto_generate_name?: boolean
}

// 流式响应数据接口
interface StreamResponse {
    event: string
    type: string
    content: string
    conversation_id?: string
    message_id?: string
    created_at?: number
    task_id?: string
    workflow_run_id?: string
    answer?: string
}

// 发送消息响应接口
interface SendMessageResponse {
    conversation_id: string
    message_id: string
    answer: string
    created_at: number
    task_id?: string
    workflow_run_id?: string
}

// 请求配置接口
interface RequestConfig {
    url: string
    data: any
    header: {
        'Content-Type': string
    }
}

export const robApi = {
    // 发送对话信息
    sendMessage: async (message: string, onStream?: (content: string) => void): Promise<SendMessageResponse> => {
        const params: SendMessageRequest = {
            inputs: {},
            query: message,
            response_mode: 'streaming',
            conversation_id: '',
            user: 'abc-123',
            auto_generate_name: true
        }

        try {
            const res = await service.request({
                url: '/chat-messages',
                method: 'POST',
                data: params,
                // 设置响应类型为text
                responseType: 'text'
            })

            // console.log('Raw response:', res.data) // 添加日志查看原始响应

            // 处理流式响应
            if (res.statusCode === 200) {
                let fullResponse = ''
                let conversationId = ''
                let messageId = ''
                let taskId = ''
                let workflowRunId = ''
                let createdAt = 0
                const lines = res.data.split('\n\n')
                console.log(lines, 'lines222222')

                for (const line of lines) {
                    if (!line.trim()) continue

                    try {
                        if (line.startsWith('data:')) {
                            const jsonStr = line.slice(5).trim()
                            const data: StreamResponse = JSON.parse(jsonStr)
                            if (data.event === 'message') {
                                const newContent = data.answer || ''
                                fullResponse += newContent
                                conversationId = data.conversation_id || conversationId
                                messageId = data.message_id || messageId
                                taskId = data.task_id || taskId
                                workflowRunId = data.workflow_run_id || workflowRunId
                                createdAt = data.created_at || createdAt
                                // 立即调用回调函数，更新UI
                                onStream?.(fullResponse)
                            }
                        }
                    } catch (e) {
                        console.error('解析流式数据失败:', e)
                    }
                }

                // 返回最终结果
                return {
                    conversation_id: conversationId,
                    message_id: messageId,
                    answer: fullResponse,
                    created_at: createdAt,
                    task_id: taskId,
                    workflow_run_id: workflowRunId
                }
            } else {
                throw new Error(`请求失败: ${res.statusCode}`)
            }
        } catch (error) {
            console.error('发送消息失败:', error)
            throw error
        }
    },

    // 创建新会话
    createConversation: async (params: {
        user: string
        auto_generate_name?: boolean
    }): Promise<{ conversation_id: string }> => {
        try {
            const res = await service.request({
                url: '/conversations',
                method: 'POST',
                data: params
            })
            return res.data
        } catch (error) {
            console.error('创建会话失败:', error)
            throw error
        }
    },

    // 重命名会话
    renameConversation: async (conversationId: string, params: {
        name?: string
        auto_generate?: boolean
    }): Promise<void> => {
        try {
            await service.request({
                url: `/conversations/${conversationId}`,
                method: 'PUT',
                data: params
            })
        } catch (error) {
            console.error('重命名会话失败:', error)
            throw error
        }
    }
}